package com.efounder.chat.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.efounder.chat.model.ChatListItem;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.message.struct.IMStruct002;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


/**
 * 聊天列表管理
 *
 * @author yqs
 */
public class ChatListDBManager {
    private SQLiteDatabase db;
    private int loginUserId;
    private SimpleDateFormat dateFormat;

    public ChatListDBManager() {

        this.loginUserId = Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID, "0")).intValue();
        dateFormat = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
        this.db = GetDBHelper.getInstance().getDb();

    }

    /**
     * 聊天列表插入或更新新聊天（单个）
     *
     * @param chatListItem
     * @return
     */
    public long insertOrUpdateChatList(ChatListItem chatListItem) {
        ContentValues values = getChatListContentValues(chatListItem);

        // 生成的sql是 INSERT INTRO OR REPLACE INTO 这样的 (如果存在就替换存在的字段值. 存在的判断标准是主键冲突, 这里的主键是userId).
        return this.db.insertWithOnConflict("ChatList", null, values, SQLiteDatabase.CONFLICT_REPLACE);

    }

    /**
     * 聊天列表插入新聊天（多个）
     *
     * @param chatItemList
     * @return
     */
    public void insertOrUpdateChatList(List<ChatListItem> chatItemList) {
        this.db.beginTransaction();
        for (Iterator<ChatListItem> localIterator = chatItemList.iterator(); localIterator
                .hasNext(); ) {
            ChatListItem chatListItem = (ChatListItem) localIterator.next();
            insertOrUpdateChatList(chatListItem);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

//	/**
//	 * 更新聊天列表（单个）
//	 *
//	 * @param chatListItem
//	 * @return
//	 */
//	public int update(ChatListItem chatListItem) {
//		SQLiteDatabase db = helper.getWritableDatabase();
//		ContentValues values = getChatListContentValues(chatListItem);
//
//		String whereClause = "loginUserId=? and userId = ? and type =?";
//		String[] whereArgs = { String.valueOf(chatListItem.getLoginUserId()),String.valueOf(chatListItem.getUserId()),
//				String.valueOf(chatListItem.getType()) };
//		return db.update("ChatList", values, whereClause, whereArgs);
//	}
//
//	/**
//	 * 更新聊天列表存在的列表改为可用
//	 *
//	 * @param chatListItem
//	 * @return
//	 */
//	public int updateState(ChatListItem chatListItem) {
//		db.execSQL("update ChatList set enable=1,messageid="
//				+ chatListItem.getStruct002().getMsgId() + " where userId = "
//				+ chatListItem.getUserId());
//		return 1;
//	}
//
//	/**
//	 * 更新聊天列表（多个）
//	 *
//	 * @param chatItemList
//	 * @return
//	 */
//	public void update(List<ChatListItem> chatItemList) {
//		this.db.beginTransaction();
//		for (Iterator<ChatListItem> localIterator = chatItemList.iterator(); localIterator
//				.hasNext();) {
//			ChatListItem chatListItem = (ChatListItem) localIterator.next();
//			update(chatListItem);
//		}
//		this.db.setTransactionSuccessful();
//		this.db.endTransaction();
//	}

//	
//	/**
//	 * 更新聊天列表是否置顶
//	 *
//	 * @return
//	 */
//	public void setIsTop(int currentId,Boolean istop,int type) {
//		int a = istop==true?1:0;
//		String sql = "update  ChatList  set istop ="+a+" where currentId = "+currentId+" and type="+ type;
//		db.execSQL(sql);
//	}
//	/**
//	 * 更新聊天列表是否免打扰
//	 *
//	 * @return
//	 */
//	public void setIsBother(int currentId,Boolean isBother,int type) {
//		int a = isBother==true?1:0;
//		String sql = "update  ChatList  set isbother ="+a+" where currentId = "+currentId +" and type="+ type;
//		db.execSQL(sql);
//	}
//	/**
//	 * 更新chatlist名称
//	 *
//	 * @return
//	 */
//	public void setItemValue(int id,String columnName,String value,int type) {
//
////		String sql = "update  ChatList set "+columnName+"= "+value+" where id = "+id;
////		db.execSQL(sql);
//		String sql = "update  ChatList set "+columnName+"=? where currentId=? and type =?";
//		db.execSQL(sql, new Object[]{value,id,type});
//	}

    /**
     * 删除聊天列表子项（单个）
     *
     * @param chatListItem
     * @return
     */
    public void delete(ChatListItem chatListItem) {
//		String whereClause = " loginUserId = ? userId=? and type = ?up";
//		String[] whereArgs = {String.valueOf(chatListItem.getLoginUserId()) ,String.valueOf(chatListItem.getUserId()),String.valueOf(chatListItem.getType()) };
//		return this.db.delete("ChatList", whereClause, whereArgs);
        String sql = "update chatlist set enable = 0 where loginUserId = ? and userId = ? and chatType = ?;";
        Object[] objects = {String.valueOf(loginUserId), String.valueOf(chatListItem.getUserId()),
                String.valueOf(chatListItem.getChatType())};
        this.db.execSQL(sql, objects);

    }

    /**
     * 删除聊天列表子项（多个）
     *
     * @param chatItemList
     * @return
     */
    public void delete(List<ChatListItem> chatItemList) {
        this.db.beginTransaction();
        for (Iterator<ChatListItem> localIterator = chatItemList.iterator(); localIterator
                .hasNext(); ) {
            ChatListItem chatListItem = (ChatListItem) localIterator.next();
            delete(chatListItem);
        }
        this.db.setTransactionSuccessful();
        this.db.endTransaction();
    }

    /**
     * 删除所有聊天列表）
     *
     * @return
     */
//	public void delete() {
//		db.execSQL("delete from ChatList where loginUserId = "+loginUserId+";");
//	}

    /**
     * 查找聊天列表子项
     *
     * @return
     */
    public ChatListItem queryChatListItem(int userId, int chatType) {

//		String sql1 = "select * from ChatList,Message,User where chatlist.userId = User.userId"
//				+ " and ChatList.messageId = message.messageid and ChatList.enable =1"
//				+ " and Message.enable =1 and User.enable =1 and loginUserid ="+loginUserId +
//				" and friends.userid = user.userid and friends.loginUserid = "+ loginUserId +
//				 " order by Message.time desc;";

        String sql = "select * from ChatList where loginUserid =" + loginUserId + " and userId =" + userId +
                " and chatType =" + chatType + " and enable =1;";
        List<ChatListItem> list = query(sql);

        return list.size() == 0 ? null : list.get(0);
    }

    /**
     * 查找所有聊天列表
     *
     * @return
     */
    public List<ChatListItem> queryAll() {

//		String sql1 = "select * from ChatList,Message,User where chatlist.userId = User.userId"
//				+ " and ChatList.messageId = message.messageid and ChatList.enable =1"
//				+ " and Message.enable =1 and User.enable =1 and loginUserid ="+loginUserId +
//				" and friends.userid = user.userid and friends.loginUserid = "+ loginUserId +
//				 " order by Message.time desc;";

        String sql = "select * from ChatList where loginUserid =" + loginUserId + " and enable =1;";
        List<ChatListItem> list = query(sql);

        return list;
    }

    public List<ChatListItem> query(String sql) {
        return query(sql, null);
    }

    public List<ChatListItem> query(String sql, String[] selectionArgs) {
        List<ChatListItem> list = new ArrayList<ChatListItem>();
        Cursor cursor = this.db.rawQuery(sql, selectionArgs);
        while (cursor.moveToNext()) {
            ChatListItem chatListItem = new ChatListItem();

            IMStruct002 struct002 = new IMStruct002();

            chatListItem.setLoginUserId(cursor.getInt(cursor.getColumnIndex("loginUserId")));
//			chatListItem.setBadgernum(cursor.getInt(cursor
//					.getColumnIndex("unReadCount")));
            chatListItem.setBadgernum(-1);
            chatListItem.setUserId(cursor.getInt(cursor.getColumnIndex("userId")));
            struct002.setMsgId(cursor.getInt(cursor.getColumnIndex("messageId")));
            struct002.setMessageID(cursor.getString(cursor.getColumnIndex("msgID")));
            chatListItem.setChatType(cursor.getInt(cursor.getColumnIndex("chatType")));
            chatListItem.setStruct002(struct002);
//			chatListItem.setAvatar(cursor.getString(cursor
//					.getColumnIndex("avatar")));
//			chatListItem
//					.setName(cursor.getString(cursor.getColumnIndex("name")));
//			chatListItem.setType(cursor.getInt(cursor.getColumnIndex("type")));
//			chatListItem
//					.setIsTop(cursor.getInt(cursor.getColumnIndex("isTop")) == 1 ? true
//							: false);
//			chatListItem.setIsBother(cursor.getInt(cursor
//					.getColumnIndex("isbother")) == 1 ? true : false);
//
//			struct002
//					.setMsgId(cursor.getInt(cursor.getColumnIndex("messageId")));
//			struct002.setFromUserId(cursor.getInt(cursor
//					.getColumnIndex("fromUserId")));
//			struct002.setToUserId(cursor.getInt(cursor
//					.getColumnIndex("toUserId")));
//			try {
//				Date date = this.dateFormat.parse(cursor.getString(cursor
//						.getColumnIndex("time")));
//				struct002.setTime(date.getTime());
//			} catch (ParseException e) {
//				e.printStackTrace();
//			}
//			struct002.setToUserType((byte) cursor.getInt(cursor
//					.getColumnIndex("toUserType")));
//			struct002.setMessageChildType((byte) cursor.getInt(cursor
//					.getColumnIndex("messageChildType")));
//			struct002.setBody(cursor.getBlob(cursor.getColumnIndex("body")));
//			struct002.setState(cursor.getInt(cursor.getColumnIndex("state")));
//			chatListItem.setStruct002(struct002);

            list.add(chatListItem);
        }

        cursor.close();
        return list;
    }

    private ContentValues getChatListContentValues(ChatListItem chatListItem) {
        ContentValues values = new ContentValues();
        values.put("loginUserId", chatListItem.getLoginUserId());
        values.put("userId", chatListItem.getUserId());
        values.put("msgID", chatListItem.getStruct002().getMessageID());
        values.put("messageId", chatListItem.getStruct002().getMsgId());
        values.put("unReadCount", Integer.valueOf(chatListItem.getBadgernum()));
        values.put("chatType", Integer.valueOf(chatListItem.getChatType()));
        values.put("enable", 1);

        return values;
    }

}